package cn.dy.sbo.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.common.lib.springside.service.EntityManager;
import cn.dy.sbo.api.UserDao;
import cn.dy.sbo.model.User;
import cn.dy.sbo.util.CommonUtils;

@Component
@Transactional
public class UserManager extends EntityManager<User, Long>
{
    @Autowired
    private UserDao userDao;

    @Override
    protected UserDao getEntityDao()
    {
        return userDao;
    }

    public User getByUserName(String username)
    {
        return userDao.findUniqueBy("username", username);
    }

    public void used(Long id)
    {
        updateValid(id, true);
    }

    private void updateValid(Long id, boolean flag)
    {
        userDao.updateValid(id, flag);
    }

    public void unUsed(Long id)
    {
        updateValid(id, false);
    }

    public boolean isExistByName(String newName, String oldName)
    {
        return !userDao.isPropertyUnique("name", newName, oldName);
    }

    public boolean isTrue(Long userId, String oldPass) throws Exception
    {
        User user = userDao.get(userId);
        oldPass = CommonUtils.encryptMD5(oldPass);
        if (user.getPassword().equals(oldPass))
        {
            return true;
        }
        return false;
    }
}